from typing import List, Dict
from datetime import datetime
from services.frailty_service import FrailtyService

class ReportGenerator:
    """报告生成器"""
    
    @staticmethod
    def detect_survey_type(surveys: List[dict]) -> str:
        """检测问卷类型"""
        if not surveys:
            return "unknown"
        
        # 检查第一个问卷的字段来判断类型
        first_survey = surveys[0]
        
        # PSQI睡眠质量评估特征字段
        psqi_fields = ['SL01', 'SL02', 'SL03', 'SL04', 'SL051', 'SL052', 'SL06', 'SL07', 'subjective_sleep_quality', 'sleep_latency']
        if any(field in first_survey for field in psqi_fields):
            return "psqi"
        
        # Fried衰弱评估特征字段
        frailty_fields = ['weightLoss', 'walkTime', 'gripStrength', 'physicalActivity']
        if any(field in first_survey for field in frailty_fields):
            return "frailty"
        
        # Rockwood CFS问卷特征字段
        rockwood_fields = ['cfsScore', 'functionalAssessment', 'mobilityLevel']
        if any(field in first_survey for field in rockwood_fields):
            return "rockwood"
        
        # GPM疼痛量表特征字段
        gpm_fields = ['restPain', 'activityPain', 'painFrequency', 'dressingAbility', 'anxiety']
        if any(field in first_survey for field in gpm_fields):
            return "gpm"
        
        # NRS疼痛评估特征字段
        nrs_fields = ['currentPain', 'worstPain24h', 'leastPain24h', 'averagePain24h', 'functionalImpact']
        if any(field in first_survey for field in nrs_fields):
            return "nrs"
        
        # HAMD抑郁评估特征字段
        hamd_fields = ['depression', 'guilt', 'suicide', 'insomnia_early', 'insomnia_middle']
        if any(field in first_survey for field in hamd_fields):
            return "hamd"
        
        return "unknown"
    
    @staticmethod
    def generate_summary_report(surveys: List[dict], survey_id: str) -> str:
        """生成汇总报告"""
        survey_type = ReportGenerator.detect_survey_type(surveys)
        
        if survey_type == "psqi":
            return ReportGenerator.generate_psqi_summary_report(surveys, survey_id)
        elif survey_type == "frailty":
            return ReportGenerator.generate_frailty_summary_report(surveys, survey_id)
        elif survey_type == "rockwood":
            return ReportGenerator.generate_rockwood_summary_report(surveys, survey_id)
        elif survey_type == "gpm":
            return ReportGenerator.generate_gpm_summary_report(surveys, survey_id)
        elif survey_type == "nrs":
            return ReportGenerator.generate_nrs_summary_report(surveys, survey_id)
        elif survey_type == "hamd":
            return ReportGenerator.generate_hamd_summary_report(surveys, survey_id)
        else:
            return f"""未知问卷类型汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

暂无法识别问卷类型
"""
    
    @staticmethod
    def generate_frailty_summary_report(surveys: List[dict], survey_id: str) -> str:
        """生成Fried衰弱评估汇总报告"""
        # 获取统计数据
        frailty_stats = FrailtyService.get_frailty_statistics(surveys)
        demographic_stats = FrailtyService.get_demographic_statistics(surveys)
        indicator_stats = FrailtyService.get_indicator_statistics(surveys)
        
        total_count = frailty_stats['total']
        if total_count == 0:
            return f"""Fried衰弱评估汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

暂无数据
"""
        
        report = f"""Fried衰弱评估汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

=== 基本统计 ===
总问卷数: {total_count}
平均年龄: {demographic_stats['avg_age']:.1f}岁
性别分布: 男性 {demographic_stats['male_count']}人 ({demographic_stats['male_percentage']:.1f}%), 女性 {demographic_stats['female_count']}人 ({demographic_stats['female_percentage']:.1f}%)

=== 衰弱评估结果 ===
正常 (0-2分): {frailty_stats['normal']}人 ({frailty_stats['normal']/total_count*100:.1f}%)
衰弱前期 (3-4分): {frailty_stats['pre_frail']}人 ({frailty_stats['pre_frail']/total_count*100:.1f}%)
衰弱 (≥5分): {frailty_stats['frail']}人 ({frailty_stats['frail']/total_count*100:.1f}%)

=== 各项指标统计 ===
"""
        
        # 添加各项指标统计
        for indicator_name, stats in indicator_stats.items():
            report += f"{indicator_name}: {stats['positive']}人 ({stats['percentage']:.1f}%)\n"
        
        return report
    
    @staticmethod
    def generate_hamd_summary_report(surveys: List[dict], survey_id: str) -> str:
        """生成HAMD抑郁评估汇总报告"""
        total_count = len(surveys)
        if total_count == 0:
            return f"""HAMD抑郁评估汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

暂无数据
"""
        
        # 统计抑郁程度分布
        severity_stats = {'正常': 0, '轻度抑郁': 0, '中度抑郁': 0, '重度抑郁': 0}
        total_scores = []
        age_sum = 0
        male_count = 0
        female_count = 0
        
        for survey in surveys:
            total_score = survey.get('totalScore', 0)
            total_scores.append(total_score)
            
            # 抑郁程度分类
            if total_score < 8:
                severity_stats['正常'] += 1
            elif total_score < 20:
                severity_stats['轻度抑郁'] += 1
            elif total_score < 35:
                severity_stats['中度抑郁'] += 1
            else:
                severity_stats['重度抑郁'] += 1
            
            # 统计年龄和性别
            age_sum += survey.get('age', 0)
            if survey.get('gender') == '男':
                male_count += 1
            else:
                female_count += 1
        
        avg_age = age_sum / total_count if total_count > 0 else 0
        avg_score = sum(total_scores) / total_count if total_count > 0 else 0
        
        report = f"""HAMD抑郁评估汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

=== 基本统计 ===
总问卷数: {total_count}
平均年龄: {avg_age:.1f}岁
性别分布: 男性 {male_count}人 ({male_count/total_count*100:.1f}%), 女性 {female_count}人 ({female_count/total_count*100:.1f}%)
平均总分: {avg_score:.1f}分

=== 抑郁程度分布 ===
正常 (<8分): {severity_stats['正常']}人 ({severity_stats['正常']/total_count*100:.1f}%)
轻度抑郁 (8-19分): {severity_stats['轻度抑郁']}人 ({severity_stats['轻度抑郁']/total_count*100:.1f}%)
中度抑郁 (20-34分): {severity_stats['中度抑郁']}人 ({severity_stats['中度抑郁']/total_count*100:.1f}%)
重度抑郁 (≥35分): {severity_stats['重度抑郁']}人 ({severity_stats['重度抑郁']/total_count*100:.1f}%)

=== 各项目平均分 ===
"""
        
        # 计算各项目平均分
        item_names = [
            '抑郁情绪', '罪恶感', '自杀', '入睡困难', '睡眠不深',
            '早醒', '工作和兴趣', '迟缓', '激越', '精神性焦虑',
            '躯体性焦虑', '胃肠道症状', '全身症状', '生殖器症状',
            '疑病', '体重减轻', '自知力'
        ]
        
        item_fields = [
             'depression', 'guilt', 'suicide', 'insomnia_early', 'insomnia_middle',
             'insomnia_late', 'work_interests', 'retardation', 'agitation', 'anxiety_psychic',
             'anxiety_somatic', 'somatic_gastrointestinal', 'somatic_general', 'genital_symptoms',
             'hypochondriasis', 'loss_of_weight', 'insight'
         ]
        
        for i, (name, field) in enumerate(zip(item_names, item_fields)):
            scores = [survey.get(field, 0) for survey in surveys]
            avg_score = sum(scores) / len(scores) if scores else 0
            report += f"{i+1:2d}. {name}: {avg_score:.2f}分\n"
        
        return report
    
    @staticmethod
    def generate_hamd_csv_report(group_dir: str) -> str:
        """生成HAMD问卷CSV报告"""
        import os
        import json
        
        surveys = []
        
        # 读取所有HAMD问卷JSON文件
        for filename in os.listdir(group_dir):
            if filename.endswith('.json') and 'HAMD' in filename:
                filepath = os.path.join(group_dir, filename)
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        survey_data = json.load(f)
                        surveys.append(survey_data)
                except Exception as e:
                    print(f"读取文件 {filename} 失败: {e}")
        
        if not surveys:
            return ""
        
        # CSV头部
        headers = [
            '问卷编号', '患者姓名', '年龄', '性别', '记录人', '创建时间',
            '抑郁情绪', '罪恶感', '自杀', '入睡困难', '睡眠不深', '早醒',
            '工作和兴趣', '迟缓', '激越', '精神性焦虑', '躯体性焦虑',
            '胃肠道症状', '全身症状', '生殖器症状', '疑病', '体重减轻', '自知力',
            '总分', '抑郁程度', '诊断结果'
        ]
        
        csv_content = ','.join(headers) + '\n'
        
        # 数据行
        for survey in surveys:
            row = [
                survey.get('surveyId', ''),
                survey.get('patientName', ''),
                str(survey.get('age', '')),
                survey.get('gender', ''),
                survey.get('recorderName', ''),
                survey.get('createdAt', ''),
                str(survey.get('depression', 0)),
                str(survey.get('guilt', 0)),
                str(survey.get('suicide', 0)),
                str(survey.get('insomnia_early', 0)),
                str(survey.get('insomnia_middle', 0)),
                str(survey.get('insomnia_late', 0)),
                str(survey.get('work_interests', 0)),
                str(survey.get('retardation', 0)),
                str(survey.get('agitation', 0)),
                str(survey.get('anxiety_psychic', 0)),
                str(survey.get('anxiety_somatic', 0)),
                str(survey.get('somatic_gastrointestinal', 0)),
                str(survey.get('somatic_general', 0)),
                str(survey.get('genital_symptoms', 0)),
                str(survey.get('hypochondriasis', 0)),
                str(survey.get('loss_of_weight', 0)),
                str(survey.get('insight', 0)),
                str(survey.get('totalScore', 0)),
                survey.get('severity', ''),
                survey.get('diagnosis', '')
            ]
            
            # 处理包含逗号的字段
            processed_row = []
            for field in row:
                if ',' in field or '"' in field:
                    field = '"' + field.replace('"', '""') + '"'
                processed_row.append(field)
            
            csv_content += ','.join(processed_row) + '\n'
        
        return csv_content
    
    @staticmethod
    def generate_psqi_summary_report(surveys: List[dict], survey_id: str) -> str:
        """生成PSQI睡眠质量评估汇总报告"""
        total_count = len(surveys)
        if total_count == 0:
            return f"""PSQI睡眠质量评估汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

暂无数据
"""
        
        # 计算基本统计
        total_age = sum(survey.get('age', 0) for survey in surveys)
        avg_age = total_age / total_count if total_count > 0 else 0
        
        male_count = sum(1 for survey in surveys if survey.get('gender') == '男性')
        female_count = total_count - male_count
        
        # 计算PSQI得分统计
        total_scores = [survey.get('totalScore', 0) for survey in surveys]
        avg_score = sum(total_scores) / total_count if total_count > 0 else 0
        
        # PSQI评分分级统计
        good_sleep = sum(1 for score in total_scores if score <= 5)  # 良好睡眠质量
        poor_sleep = sum(1 for score in total_scores if score > 5)   # 睡眠质量差
        
        # 各组件平均得分
        components = {
            '主观睡眠质量': '主观睡眠质量_score',
            '入睡时间': '入睡时间_score', 
            '睡眠时间': '睡眠时间_score',
            '睡眠效率': '睡眠效率_score',
            '睡眠干扰': '睡眠干扰_score',
            '催眠药物的使用': '催眠药物的使用_score',
            '日间功能障碍': '日间功能障碍_score'
        }
        
        report = f"""PSQI睡眠质量评估汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

=== 基本统计 ===
总问卷数: {total_count}
平均年龄: {avg_age:.1f}岁
性别分布: 男性 {male_count}人 ({male_count/total_count*100:.1f}%), 女性 {female_count}人 ({female_count/total_count*100:.1f}%)

=== PSQI评估结果 ===
平均PSQI总分: {avg_score:.1f}/21
良好睡眠质量 (≤5分): {good_sleep}人 ({good_sleep/total_count*100:.1f}%)
睡眠质量差 (>5分): {poor_sleep}人 ({poor_sleep/total_count*100:.1f}%)

=== 各组件平均得分 ===
"""
        
        # 添加各组件统计
        for component_name, field_name in components.items():
            scores = [survey.get(field_name, 0) for survey in surveys]
            avg_component_score = sum(scores) / len(scores) if scores else 0
            max_score = 3  # PSQI各组件最高分都是3分
            report += f"{component_name}: {avg_component_score:.1f}/{max_score}\n"
        
        return report
    
    @staticmethod
    def generate_rockwood_summary_report(surveys: List[dict], survey_id: str) -> str:
        """生成Rockwood CFS汇总报告"""
        total_count = len(surveys)
        if total_count == 0:
            return f"""Rockwood临床衰弱量表(CFS)汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

暂无数据
"""
        
        # 计算基本统计
        total_age = sum(survey.get('age', 0) for survey in surveys)
        avg_age = total_age / total_count if total_count > 0 else 0
        
        # 性别统计
        male_count = sum(1 for survey in surveys if survey.get('gender') == 'male')
        female_count = total_count - male_count
        
        # CFS评分统计
        cfs_scores = [int(survey.get('cfsScore', 0)) for survey in surveys]
        avg_cfs_score = sum(cfs_scores) / total_count if total_count > 0 else 0
        
        # CFS分级统计
        robust_count = sum(1 for score in cfs_scores if 1 <= score <= 3)  # 健壮至管理良好的慢性疾病
        vulnerable_count = sum(1 for score in cfs_scores if score == 4)   # 易损状态
        mild_frail_count = sum(1 for score in cfs_scores if 5 <= score <= 6)  # 轻度至中度衰弱
        severe_frail_count = sum(1 for score in cfs_scores if 7 <= score <= 8)  # 重度至极重度衰弱
        terminal_count = sum(1 for score in cfs_scores if score == 9)     # 终末期
        
        # 功能状态统计
        functional_stats = {}
        functional_options = ['independent', 'minimal_help', 'moderate_help', 'significant_help', 'total_dependence']
        for option in functional_options:
            count = sum(1 for survey in surveys if survey.get('functionalAssessment') == option)
            functional_stats[option] = count
        
        report = f"""Rockwood临床衰弱量表(CFS)汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

=== 基本统计 ===
总问卷数: {total_count}
平均年龄: {avg_age:.1f}岁
性别分布: 男性 {male_count}人 ({male_count/total_count*100:.1f}%), 女性 {female_count}人 ({female_count/total_count*100:.1f}%)

=== CFS评估结果 ===
平均CFS评分: {avg_cfs_score:.1f}/9
健壮至管理良好的慢性疾病 (1-3分): {robust_count}人 ({robust_count/total_count*100:.1f}%)
易损状态 (4分): {vulnerable_count}人 ({vulnerable_count/total_count*100:.1f}%)
轻度至中度衰弱 (5-6分): {mild_frail_count}人 ({mild_frail_count/total_count*100:.1f}%)
重度至极重度衰弱 (7-8分): {severe_frail_count}人 ({severe_frail_count/total_count*100:.1f}%)
终末期 (9分): {terminal_count}人 ({terminal_count/total_count*100:.1f}%)

=== 功能状态分布 ===
完全独立: {functional_stats.get('independent', 0)}人 ({functional_stats.get('independent', 0)/total_count*100:.1f}%)
偶尔需要轻微帮助: {functional_stats.get('minimal_help', 0)}人 ({functional_stats.get('minimal_help', 0)/total_count*100:.1f}%)
经常需要中等程度帮助: {functional_stats.get('moderate_help', 0)}人 ({functional_stats.get('moderate_help', 0)/total_count*100:.1f}%)
需要大量帮助: {functional_stats.get('significant_help', 0)}人 ({functional_stats.get('significant_help', 0)/total_count*100:.1f}%)
完全依赖他人: {functional_stats.get('total_dependence', 0)}人 ({functional_stats.get('total_dependence', 0)/total_count*100:.1f}%)
"""
        
        return report
    
    @staticmethod
    def generate_gpm_summary_report(surveys: List[dict], survey_id: str) -> str:
        """生成GPM疼痛量表汇总报告"""
        total_count = len(surveys)
        if total_count == 0:
            return f"""GPM疼痛量表汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

暂无数据
"""
        
        # 计算基本统计
        total_age = sum(survey.get('age', 0) for survey in surveys)
        avg_age = total_age / total_count if total_count > 0 else 0
        
        # 性别统计
        male_count = sum(1 for survey in surveys if survey.get('gender') == 'male')
        female_count = total_count - male_count
        
        # GPM总分统计
        total_scores = [survey.get('totalScore', 0) for survey in surveys]
        avg_score = sum(total_scores) / total_count if total_count > 0 else 0
        
        # 疼痛等级分布统计
        no_pain = sum(1 for score in total_scores if score == 0)
        mild_pain = sum(1 for score in total_scores if 1 <= score <= 3)
        moderate_pain = sum(1 for score in total_scores if 4 <= score <= 6)
        severe_pain = sum(1 for score in total_scores if 7 <= score <= 10)
        
        # 维度得分统计
        dimension1_scores = [survey.get('dimension1Score', 0) for survey in surveys]
        dimension2_scores = [survey.get('dimension2Score', 0) for survey in surveys]
        dimension3_scores = [survey.get('dimension3Score', 0) for survey in surveys]
        
        avg_dim1 = sum(dimension1_scores) / total_count if total_count > 0 else 0
        avg_dim2 = sum(dimension2_scores) / total_count if total_count > 0 else 0
        avg_dim3 = sum(dimension3_scores) / total_count if total_count > 0 else 0
        
        # 疼痛部位统计
        pain_locations = {}
        for survey in surveys:
            location = survey.get('painLocation', '未指定')
            pain_locations[location] = pain_locations.get(location, 0) + 1
        
        report = f"""GPM疼痛量表汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

=== 基本统计 ===
总问卷数: {total_count}
平均年龄: {avg_age:.1f}岁
性别分布: 男性 {male_count}人 ({male_count/total_count*100:.1f}%), 女性 {female_count}人 ({female_count/total_count*100:.1f}%)

=== GPM疼痛评估结果 ===
平均总分: {avg_score:.1f}/10
无疼痛 (0分): {no_pain}人 ({no_pain/total_count*100:.1f}%)
轻度疼痛 (1-3分): {mild_pain}人 ({mild_pain/total_count*100:.1f}%)
中度疼痛 (4-6分): {moderate_pain}人 ({moderate_pain/total_count*100:.1f}%)
重度疼痛 (7-10分): {severe_pain}人 ({severe_pain/total_count*100:.1f}%)

=== 各维度平均得分 ===
维度一(疼痛强度): {avg_dim1:.1f}
维度二(疼痛频率): {avg_dim2:.1f}
维度三(日常活动影响): {avg_dim3:.1f}

=== 疼痛部位分布 ===
"""
        
        # 添加疼痛部位统计
        for location, count in pain_locations.items():
            percentage = count / total_count * 100
            report += f"{location}: {count}人 ({percentage:.1f}%)\n"
        
        return report
    
    @staticmethod
    def generate_nrs_summary_report(surveys: List[dict], survey_id: str) -> str:
        """生成NRS疼痛评估汇总报告"""
        total_count = len(surveys)
        if total_count == 0:
            return f"""NRS疼痛评估量表汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

暂无数据
"""
        
        # 计算基本统计
        total_age = sum(survey.get('age', 0) for survey in surveys)
        avg_age = total_age / total_count if total_count > 0 else 0
        
        # 性别统计
        male_count = sum(1 for survey in surveys if survey.get('gender') == 'male')
        female_count = total_count - male_count
        
        # NRS评分统计
        nrs_scores = [survey.get('nrsScore', 0) for survey in surveys]
        avg_nrs_score = sum(nrs_scores) / total_count if total_count > 0 else 0
        
        # 疼痛程度分级统计
        no_pain = sum(1 for score in nrs_scores if score == 0)
        mild_pain = sum(1 for score in nrs_scores if 1 <= score <= 3)
        moderate_pain = sum(1 for score in nrs_scores if 4 <= score <= 6)
        severe_pain = sum(1 for score in nrs_scores if 7 <= score <= 10)
        
        # 疼痛持续时间统计
        duration_stats = {}
        duration_options = ['acute', 'subacute', 'chronic']
        for option in duration_options:
            count = sum(1 for survey in surveys if survey.get('painDuration') == option)
            duration_stats[option] = count
        
        # 疼痛性质统计
        nature_stats = {}
        nature_options = ['sharp', 'dull', 'burning', 'throbbing', 'cramping', 'other']
        for option in nature_options:
            count = sum(1 for survey in surveys if survey.get('painNature') == option)
            nature_stats[option] = count
        
        # 疼痛部位统计
        location_stats = {}
        for survey in surveys:
            location = survey.get('painLocation', '未指定')
            location_stats[location] = location_stats.get(location, 0) + 1
        
        report = f"""NRS疼痛评估量表汇总报告
问卷组编号: {survey_id}
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

=== 基本统计 ===
总问卷数: {total_count}
平均年龄: {avg_age:.1f}岁
性别分布: 男性 {male_count}人 ({male_count/total_count*100:.1f}%), 女性 {female_count}人 ({female_count/total_count*100:.1f}%)

=== NRS疼痛评估结果 ===
平均NRS评分: {avg_nrs_score:.1f}/10
无疼痛 (0分): {no_pain}人 ({no_pain/total_count*100:.1f}%)
轻度疼痛 (1-3分): {mild_pain}人 ({mild_pain/total_count*100:.1f}%)
中度疼痛 (4-6分): {moderate_pain}人 ({moderate_pain/total_count*100:.1f}%)
重度疼痛 (7-10分): {severe_pain}人 ({severe_pain/total_count*100:.1f}%)

=== 疼痛持续时间分布 ===
急性疼痛: {duration_stats.get('acute', 0)}人 ({duration_stats.get('acute', 0)/total_count*100:.1f}%)
亚急性疼痛: {duration_stats.get('subacute', 0)}人 ({duration_stats.get('subacute', 0)/total_count*100:.1f}%)
慢性疼痛: {duration_stats.get('chronic', 0)}人 ({duration_stats.get('chronic', 0)/total_count*100:.1f}%)

=== 疼痛性质分布 ===
锐痛: {nature_stats.get('sharp', 0)}人 ({nature_stats.get('sharp', 0)/total_count*100:.1f}%)
钝痛: {nature_stats.get('dull', 0)}人 ({nature_stats.get('dull', 0)/total_count*100:.1f}%)
灼痛: {nature_stats.get('burning', 0)}人 ({nature_stats.get('burning', 0)/total_count*100:.1f}%)
搏动性疼痛: {nature_stats.get('throbbing', 0)}人 ({nature_stats.get('throbbing', 0)/total_count*100:.1f}%)
痉挛性疼痛: {nature_stats.get('cramping', 0)}人 ({nature_stats.get('cramping', 0)/total_count*100:.1f}%)
其他: {nature_stats.get('other', 0)}人 ({nature_stats.get('other', 0)/total_count*100:.1f}%)

=== 疼痛部位分布 ===
"""
        
        # 添加疼痛部位统计
        for location, count in location_stats.items():
            percentage = count / total_count * 100
            report += f"{location}: {count}人 ({percentage:.1f}%)\n"
        
        return report
    
    @staticmethod
    def generate_csv_report(surveys: List[dict]) -> str:
        """生成CSV格式的数据报告"""
        survey_type = ReportGenerator.detect_survey_type(surveys)
        
        if survey_type == "psqi":
            return ReportGenerator.generate_psqi_csv_report(surveys)
        elif survey_type == "frailty":
            return ReportGenerator.generate_frailty_csv_report(surveys)
        elif survey_type == "rockwood":
            return ReportGenerator.generate_rockwood_csv_report(surveys)
        elif survey_type == "gpm":
            return ReportGenerator.generate_gpm_csv_report(surveys)
        elif survey_type == "nrs":
            return ReportGenerator.generate_nrs_csv_report(surveys)
        else:
            return "问卷类型,数据\n未知类型,无法生成CSV报告\n"
    
    @staticmethod
    def generate_frailty_csv_report(surveys: List[dict]) -> str:
        """生成Fried衰弱评估CSV报告"""
        headers = [
            "患者姓名", "年龄", "性别", "身高", "体重", "电话",
            "体重下降", "步行时间", "握力", "体力活动", "疲劳感1", "疲劳感2",
            "总分", "评估结果", "记录人", "记录时间", "备注"
        ]
        
        csv_content = ",".join(headers) + "\n"
        
        for survey in surveys:
            score = FrailtyService.calculate_frailty_score(survey)
            result = FrailtyService.get_frailty_result(score)
            
            row = [
                survey.get('patientName', ''),
                str(survey.get('age', '')),
                survey.get('gender', ''),
                str(survey.get('height', '')),
                str(survey.get('weight', '')),
                survey.get('phone', ''),
                str(survey.get('weightLoss', 0)),
                str(survey.get('walkTime', 0)),
                str(survey.get('gripStrength', 0)),
                str(survey.get('physicalActivity', 0)),
                str(survey.get('fatigue1', 0)),
                str(survey.get('fatigue2', 0)),
                str(score),
                result,
                survey.get('recorderName', ''),
                survey.get('createdAt', ''),
                survey.get('remarks', '')
            ]
            
            # 处理CSV中的逗号和引号
            escaped_row = []
            for field in row:
                if ',' in field or '"' in field or '\n' in field:
                    field = '"' + field.replace('"', '""') + '"'
                escaped_row.append(field)
            
            csv_content += ",".join(escaped_row) + "\n"
        
        return csv_content
    
    @staticmethod
    def generate_psqi_csv_report(surveys: List[dict]) -> str:
        """生成PSQI睡眠质量评估CSV报告（包含完整问卷选项）"""
        headers = [
            # 基本信息
            "患者姓名", "年龄", "性别", "电话", "评估日期",
            # 睡眠习惯
            "SL01_上床时间", "SL02_入睡时间_分钟", "SL03_起床时间", "SL04_实际睡眠时间_小时",
            # 睡眠干扰
            "SL051_入睡困难", "SL052_夜间易醒", "SL053_起床上洗手间", "SL054_呼吸不畅",
            "SL055_鼾声咳嗽", "SL056_感到太冷", "SL057_感到太热", "SL058_做恶梦",
            "SL059_疼痛不适", "SL05X_其他问题描述", "SL05X1_其他问题程度",
            # 睡眠质量与用药
            "SL06_主观睡眠质量", "SL07_催眠药物使用",
            # 日间功能障碍
            "SL08_日间困倦", "SL09_精力不足",
            # 睡眠伙伴评估
            "SL10_睡眠伙伴情况", "SL101_高声打鼾", "SL102_呼吸暂停", "SL103_腿部抽动",
            "SL104_意识模糊", "SL10X_其他特殊情况描述", "SL105_其他特殊情况程度",
            # 评估结果
            "PSQI总分", "睡眠质量等级", "主观睡眠质量得分", "入睡时间得分", "睡眠时间得分",
            "睡眠效率得分", "睡眠干扰得分", "催眠药物使用得分", "日间功能障碍得分",
            # 记录信息
            "记录人", "记录时间", "备注"
        ]
        
        csv_content = ",".join(headers) + "\n"
        
        # 选项映射
        frequency_options = {0: "无", 1: "<1次/周", 2: "1~2次/周", 3: "≥3次/周"}
        quality_options = {0: "很好", 1: "较好", 2: "较差", 3: "很差"}
        partner_options = {1: "没有", 2: "同伴在同一房间但不同床", 3: "同伴或室友在另一房间", 4: "同伴在同一床上"}
        
        # 辅助函数：安全获取数字值
        def safe_get_int(data, key, default=0):
            value = data.get(key, default)
            if value == '' or value is None:
                return default
            try:
                return int(value)
            except (ValueError, TypeError):
                return default
        
        for survey in surveys:
            total_score = survey.get('totalScore', 0)
            sleep_quality = "良好" if total_score <= 5 else "较差"
            
            row = [
                # 基本信息
                survey.get('patientName', ''),
                str(survey.get('age', '')),
                '男性' if survey.get('gender') == 'male' else '女性' if survey.get('gender') == 'female' else survey.get('gender', ''),
                survey.get('phone', ''),
                survey.get('assessmentDate', ''),
                # 睡眠习惯
                survey.get('SL01', ''),
                str(survey.get('SL02', '')),
                survey.get('SL03', ''),
                str(survey.get('SL04', '')),
                # 睡眠干扰
                frequency_options.get(safe_get_int(survey, 'SL051'), ''),
                frequency_options.get(safe_get_int(survey, 'SL052'), ''),
                frequency_options.get(safe_get_int(survey, 'SL053'), ''),
                frequency_options.get(safe_get_int(survey, 'SL054'), ''),
                frequency_options.get(safe_get_int(survey, 'SL055'), ''),
                frequency_options.get(safe_get_int(survey, 'SL056'), ''),
                frequency_options.get(safe_get_int(survey, 'SL057'), ''),
                frequency_options.get(safe_get_int(survey, 'SL058'), ''),
                frequency_options.get(safe_get_int(survey, 'SL059'), ''),
                survey.get('SL05X', ''),
                frequency_options.get(safe_get_int(survey, 'SL05X1'), ''),
                # 睡眠质量与用药
                quality_options.get(safe_get_int(survey, 'SL06'), ''),
                frequency_options.get(safe_get_int(survey, 'SL07'), ''),
                # 日间功能障碍
                frequency_options.get(safe_get_int(survey, 'SL08'), ''),
                frequency_options.get(safe_get_int(survey, 'SL09'), ''),
                # 睡眠伙伴评估
                partner_options.get(safe_get_int(survey, 'SL10', 1), ''),
                frequency_options.get(safe_get_int(survey, 'SL101'), ''),
                frequency_options.get(safe_get_int(survey, 'SL102'), ''),
                frequency_options.get(safe_get_int(survey, 'SL103'), ''),
                frequency_options.get(safe_get_int(survey, 'SL104'), ''),
                survey.get('SL10X', ''),
                frequency_options.get(safe_get_int(survey, 'SL105'), ''),
                # 评估结果
                str(survey.get('totalScore', 0)),
                sleep_quality,
                str(survey.get('subjective_sleep_quality', 0)),
                str(survey.get('sleep_latency', 0)),
                str(survey.get('sleep_duration', 0)),
                str(survey.get('sleep_efficiency', 0)),
                str(survey.get('sleep_disturbance', 0)),
                str(survey.get('sleep_medication', 0)),
                str(survey.get('daytime_dysfunction', 0)),
                # 记录信息
                survey.get('recorderName', ''),
                survey.get('createdAt', ''),
                survey.get('remarks', '')
            ]
            
            # 处理CSV中的逗号和引号
            escaped_row = []
            for field in row:
                field_str = str(field) if field is not None else ''
                if ',' in field_str or '"' in field_str or '\n' in field_str:
                    field_str = '"' + field_str.replace('"', '""') + '"'
                escaped_row.append(field_str)
            
            csv_content += ",".join(escaped_row) + "\n"
        
        return csv_content
    
    @staticmethod
    def generate_rockwood_csv_report(surveys: List[dict]) -> str:
        """生成Rockwood CFS CSV报告"""
        headers = [
            "问答编号", "记录人姓名", "职务/身份", "记录时间",
            "被评估人姓名", "年龄", "性别", "身高(cm)", "体重(kg)", "联系电话", "评估时间", "备注",
            "CFS评分问题", "CFS评分答案", "功能状态评估问题", "功能状态评估答案", 
            "活动能力评估问题", "活动能力评估答案",
            "CFS评分", "衰弱等级", "BMI", "评估结果"
        ]
        
        csv_content = ",".join(headers) + "\n"
        
        # CFS评分与衰弱等级映射
        frailty_levels = {
            1: '非常健康', 2: '健康', 3: '管理良好的慢性疾病',
            4: '行走缓慢但不需要帮助', 5: '轻度衰弱', 6: '中度衰弱',
            7: '重度衰弱', 8: '极重度衰弱', 9: '终末期'
        }
        
        # CFS评分选项映射
        cfs_options = {
            1: '1分 - 非常健康',
            2: '2分 - 健康', 
            3: '3分 - 管理良好的慢性疾病',
            4: '4分 - 行走缓慢但不需要帮助',
            5: '5分 - 轻度衰弱',
            6: '6分 - 中度衰弱',
            7: '7分 - 重度衰弱',
            8: '8分 - 极重度衰弱',
            9: '9分 - 终末期'
        }
        
        # 功能状态映射
        functional_mapping = {
            'independent': '完全独立，无需帮助',
            'minimal_help': '偶尔需要轻微帮助',
            'moderate_help': '经常需要中等程度帮助',
            'significant_help': '需要大量帮助',
            'total_dependence': '完全依赖他人'
        }
        
        # 活动能力映射
        mobility_mapping = {
            'very_active': '非常活跃，经常运动',
            'active': '活跃，偶尔运动',
            'limited_activity': '活动受限，但能独立行走',
            'slow_walking': '行走缓慢，可能需要辅助',
            'wheelchair': '需要轮椅或长期卧床'
        }
        
        for survey in surveys:
            # 计算BMI
            bmi = ''
            if survey.get('height') and survey.get('weight'):
                height_m = float(survey['height']) / 100
                bmi = round(float(survey['weight']) / (height_m ** 2), 1)
            
            # 获取衰弱等级
            cfs_score = survey.get('cfsScore', '')
            frailty_level = frailty_levels.get(cfs_score, '') if cfs_score else ''
            cfs_answer = cfs_options.get(cfs_score, '') if cfs_score else ''
            
            # 获取功能状态和活动能力描述
            functional_desc = functional_mapping.get(survey.get('functionalAssessment', ''), survey.get('functionalAssessment', ''))
            mobility_desc = mobility_mapping.get(survey.get('mobilityLevel', ''), survey.get('mobilityLevel', ''))
            
            # 生成评估结果
            assessment_result = f"CFS评分: {cfs_score}分, 衰弱等级: {frailty_level}" if cfs_score and frailty_level else ''
            
            row = [
                survey.get('questionnaireId', ''),
                survey.get('recorderName', ''),
                survey.get('recorderPosition', ''),
                survey.get('recordTime', ''),
                survey.get('patientName', ''),
                str(survey.get('age', '')),
                '男性' if survey.get('gender') == 'male' else '女性' if survey.get('gender') == 'female' else '',
                str(survey.get('height', '')),
                str(survey.get('weight', '')),
                survey.get('phone', ''),
                survey.get('recordTime', ''),
                survey.get('remarks', ''),
                '临床衰弱量表评分',
                cfs_answer,
                '功能状态补充评估',
                functional_desc,
                '活动能力评估',
                mobility_desc,
                str(cfs_score),
                frailty_level,
                str(bmi),
                assessment_result
            ]
            
            # 处理CSV中的逗号和引号
            escaped_row = []
            for field in row:
                field_str = str(field) if field is not None else ''
                if ',' in field_str or '"' in field_str or '\n' in field_str:
                    field_str = '"' + field_str.replace('"', '""') + '"'
                escaped_row.append(field_str)
            
            csv_content += ",".join(escaped_row) + "\n"
        
        return csv_content
    
    @staticmethod
    def generate_gpm_csv_report(surveys: List[dict]) -> str:
        """生成GPM疼痛量表CSV报告"""
        headers = [
            "问答编号", "记录人姓名", "职务/身份", "记录时间",
            "被评估人姓名", "年龄", "性别", "身高(cm)", "体重(kg)", "联系电话", "评估时间", "备注",
            # 维度一：疼痛强度和频率
            "静息时疼痛程度问题", "静息时疼痛程度答案",
            "活动时疼痛程度问题", "活动时疼痛程度答案",
            "疼痛发作频率问题", "疼痛发作频率答案",
            "夜间痛醒次数问题", "夜间痛醒次数答案",
            "疼痛持续时间问题", "疼痛持续时间答案",
            # 维度二：日常生活活动能力
            "穿衣能力问题", "穿衣能力答案",
            "进食能力问题", "进食能力答案",
            "行走能力问题", "行走能力答案",
            "如厕能力问题", "如厕能力答案",
            "个人卫生问题", "个人卫生答案",
            "睡眠质量问题", "睡眠质量答案",
            "家务能力问题", "家务能力答案",
            # 维度三：心理情绪状态
            "焦虑程度问题", "焦虑程度答案",
            "抑郁程度问题", "抑郁程度答案",
            "易怒程度问题", "易怒程度答案",
            "无助感问题", "无助感答案",
            "注意力集中问题", "注意力集中答案",
            "生活乐趣问题", "生活乐趣答案",
            # 维度四：社会功能
            "社会参与问题", "社会参与答案",
            "家庭责任问题", "家庭责任答案",
            "工作能力问题", "工作能力答案",
            "亲密关系问题", "亲密关系答案",
            # 维度五：疼痛管理
            "疼痛缓解措施效果问题", "疼痛缓解措施效果答案",
            "就医主动性问题", "就医主动性答案",
            # 维度六：主观描述
            "疼痛自我描述问题", "疼痛自我描述答案",
            "优先改善需求问题", "优先改善需求答案",
            # 评估结果
            "GPM总分", "疼痛等级", "维度一得分", "维度二得分", "维度三得分", "维度四得分", "维度五得分",
            "BMI", "评估结果"
        ]
        
        csv_content = ",".join(headers) + "\n"
        
        # 选项映射
        pain_options = {
            0: "0分：无疼痛",
            1: "1分：轻微疼痛",
            2: "2分：中度疼痛",
            3: "3分：重度疼痛",
            4: "4分：剧烈疼痛"
        }
        
        frequency_options = {
            0: "0分：从未发作",
            1: "1分：偶尔发作（每周1-2次）",
            2: "2分：经常发作（每周3-5次）",
            3: "3分：频繁发作（每天1-2次）",
            4: "4分：持续存在（几乎全天疼痛）"
        }
        
        wakeup_options = {
            0: "0分：0次",
            1: "1分：1-2次/周",
            2: "2分：3-4次/周",
            3: "3分：5-6次/周",
            4: "4分：每晚≥1次"
        }
        
        duration_options = {
            0: "0分：＜1周",
            1: "1分：1-4周",
            2: "2分：1-3个月",
            3: "3分：3-6个月",
            4: "4分：＞6个月"
        }
        
        ability_options = {
            0: "0分：完全不影响",
            1: "1分：轻微影响",
            2: "2分：中度影响",
            3: "3分：重度影响",
            4: "4分：完全无法进行"
        }
        
        # 疼痛等级映射
        pain_levels = {
            'mild': '轻度疼痛',
            'moderate': '中度疼痛', 
            'severe': '重度疼痛',
            'verySevere': '极重度疼痛'
        }
        
        for survey in surveys:
            # 计算BMI
            bmi = ''
            if survey.get('height') and survey.get('weight'):
                height_m = float(survey['height']) / 100
                bmi = round(float(survey['weight']) / (height_m ** 2), 1)
            
            # 获取疼痛等级
            pain_level = pain_levels.get(survey.get('painLevel', ''), survey.get('painLevel', ''))
            
            # 生成评估结果
            total_score = survey.get('totalScore', '')
            assessment_result = f"GPM总分: {total_score}分, 疼痛等级: {pain_level}" if total_score and pain_level else ''
            
            row = [
                survey.get('questionnaireId', ''),
                survey.get('recorderName', ''),
                survey.get('recorderPosition', ''),
                survey.get('recordTime', ''),
                survey.get('patientName', ''),
                str(survey.get('age', '')),
                '男性' if survey.get('gender') == 'male' else '女性' if survey.get('gender') == 'female' else '',
                str(survey.get('height', '')),
                str(survey.get('weight', '')),
                survey.get('phone', ''),
                survey.get('recordTime', ''),
                survey.get('remarks', ''),
                # 维度一
                "静息时疼痛程度",
                pain_options.get(survey.get('restPain', ''), str(survey.get('restPain', ''))) if survey.get('restPain', '') != '' else '',
                "活动时疼痛程度",
                pain_options.get(survey.get('activityPain', ''), str(survey.get('activityPain', ''))) if survey.get('activityPain', '') != '' else '',
                "疼痛发作频率",
                frequency_options.get(survey.get('painFrequency', ''), str(survey.get('painFrequency', ''))) if survey.get('painFrequency', '') != '' else '',
                "夜间痛醒次数",
                wakeup_options.get(survey.get('nightWakeups', ''), str(survey.get('nightWakeups', ''))) if survey.get('nightWakeups', '') != '' else '',
                "疼痛持续时间",
                duration_options.get(survey.get('painDuration', ''), str(survey.get('painDuration', ''))) if survey.get('painDuration', '') != '' else '',
                # 维度二
                "穿衣能力",
                ability_options.get(survey.get('dressingAbility', ''), str(survey.get('dressingAbility', ''))) if survey.get('dressingAbility', '') != '' else '',
                "进食能力",
                ability_options.get(survey.get('eatingAbility', ''), str(survey.get('eatingAbility', ''))) if survey.get('eatingAbility', '') != '' else '',
                "行走能力",
                ability_options.get(survey.get('walkingAbility', ''), str(survey.get('walkingAbility', ''))) if survey.get('walkingAbility', '') != '' else '',
                "如厕能力",
                ability_options.get(survey.get('toiletingAbility', ''), str(survey.get('toiletingAbility', ''))) if survey.get('toiletingAbility', '') != '' else '',
                "个人卫生",
                ability_options.get(survey.get('hygieneAbility', ''), str(survey.get('hygieneAbility', ''))) if survey.get('hygieneAbility', '') != '' else '',
                "睡眠质量",
                ability_options.get(survey.get('sleepQuality', ''), str(survey.get('sleepQuality', ''))) if survey.get('sleepQuality', '') != '' else '',
                "家务能力",
                ability_options.get(survey.get('houseworkAbility', ''), str(survey.get('houseworkAbility', ''))) if survey.get('houseworkAbility', '') != '' else '',
                # 维度三
                "焦虑程度",
                ability_options.get(survey.get('anxiety', ''), str(survey.get('anxiety', ''))) if survey.get('anxiety', '') != '' else '',
                "抑郁程度",
                ability_options.get(survey.get('depression', ''), str(survey.get('depression', ''))) if survey.get('depression', '') != '' else '',
                "易怒程度",
                ability_options.get(survey.get('irritability', ''), str(survey.get('irritability', ''))) if survey.get('irritability', '') != '' else '',
                "无助感",
                ability_options.get(survey.get('helplessness', ''), str(survey.get('helplessness', ''))) if survey.get('helplessness', '') != '' else '',
                "注意力集中",
                ability_options.get(survey.get('concentration', ''), str(survey.get('concentration', ''))) if survey.get('concentration', '') != '' else '',
                "生活乐趣",
                ability_options.get(survey.get('lifeEnjoyment', ''), str(survey.get('lifeEnjoyment', ''))) if survey.get('lifeEnjoyment', '') != '' else '',
                # 维度四
                "社会参与",
                ability_options.get(survey.get('socialParticipation', ''), str(survey.get('socialParticipation', ''))) if survey.get('socialParticipation', '') != '' else '',
                "家庭责任",
                ability_options.get(survey.get('familyResponsibility', ''), str(survey.get('familyResponsibility', ''))) if survey.get('familyResponsibility', '') != '' else '',
                "工作能力",
                ability_options.get(survey.get('workAbility', ''), str(survey.get('workAbility', ''))) if survey.get('workAbility', '') != '' else '',
                "亲密关系",
                ability_options.get(survey.get('intimateRelationship', ''), str(survey.get('intimateRelationship', ''))) if survey.get('intimateRelationship', '') != '' else '',
                # 维度五
                "疼痛缓解措施效果",
                ability_options.get(survey.get('painReliefEffect', ''), str(survey.get('painReliefEffect', ''))) if survey.get('painReliefEffect', '') != '' else '',
                "就医主动性",
                ability_options.get(survey.get('medicalSeeking', ''), str(survey.get('medicalSeeking', ''))) if survey.get('medicalSeeking', '') != '' else '',
                # 维度六
                "疼痛自我描述",
                survey.get('painDescription', ''),
                "优先改善需求",
                survey.get('priorityImprovement', ''),
                # 评估结果
                str(total_score),
                pain_level,
                str(survey.get('dimension1Score', '')),
                str(survey.get('dimension2Score', '')),
                str(survey.get('dimension3Score', '')),
                str(survey.get('dimension4Score', '')),
                str(survey.get('dimension5Score', '')),
                str(bmi),
                assessment_result
            ]
            
            # 处理CSV中的逗号和引号
            escaped_row = []
            for field in row:
                field_str = str(field) if field is not None else ''
                if ',' in field_str or '"' in field_str or '\n' in field_str:
                    field_str = '"' + field_str.replace('"', '""') + '"'
                escaped_row.append(field_str)
            
            csv_content += ",".join(escaped_row) + "\n"
        
        return csv_content
    
    @staticmethod
    def generate_nrs_csv_report(surveys: List[dict]) -> str:
        """生成NRS疼痛评估CSV报告"""
        headers = [
            # 基本信息
            "患者姓名", "年龄", "性别", "诊断", "电话", "评估时间", "备注",
            # NRS疼痛评估问题和答案
            "当前疼痛程度", "当前疼痛程度_答案",
            "过去24小时最严重疼痛", "过去24小时最严重疼痛_答案", 
            "过去24小时最轻微疼痛", "过去24小时最轻微疼痛_答案",
            "过去24小时平均疼痛", "过去24小时平均疼痛_答案",
            "静息时疼痛程度", "静息时疼痛程度_答案",
            "活动时疼痛程度", "活动时疼痛程度_答案",
            "疼痛部位", "疼痛部位_答案",
            "疼痛性质", "疼痛性质_答案",
            "疼痛持续时间", "疼痛持续时间_答案",
            "疼痛诱发因素", "疼痛诱发因素_答案",
            "疼痛缓解因素", "疼痛缓解因素_答案",
            "功能影响评估", "功能影响评估_答案",
            # 评估结果
            "最高疼痛评分", "疼痛等级", "疼痛等级范围", "建议措施",
            "记录人", "记录人职位", "记录人机构", "记录人联系方式"
        ]
        
        # 疼痛持续时间映射
        duration_mapping = {
            'acute': '急性（＜1周）',
            'subacute': '亚急性（1-4周）',
            'chronic': '慢性（＞4周）'
        }
        
        # 疼痛性质映射
        character_mapping = {
            'sharp': '尖锐痛/刺痛',
            'dull': '钝痛/隐痛',
            'burning': '烧灼痛',
            'throbbing': '跳痛/搏动性痛',
            'cramping': '痉挛痛',
            'aching': '酸痛',
            'shooting': '放射痛',
            'tingling': '麻刺感'
        }
        
        csv_content = ",".join(headers) + "\n"
        
        for survey in surveys:
            # 基本信息
            patient_name = survey.get('patientName', '')
            age = survey.get('age', '')
            gender_text = '男性' if survey.get('gender') == 'male' else '女性' if survey.get('gender') == 'female' else ''
            diagnosis = survey.get('diagnosis', '')
            phone = survey.get('phone', '')
            record_time = survey.get('recordTime', '')
            remarks = survey.get('remarks', '')
            
            # NRS疼痛评估数据
            current_pain = survey.get('currentPain', '')
            worst_pain_24h = survey.get('worstPain24h', '')
            least_pain_24h = survey.get('leastPain24h', '')
            average_pain_24h = survey.get('averagePain24h', '')
            rest_pain = survey.get('restPain', '')
            activity_pain = survey.get('activityPain', '')
            pain_location = survey.get('painLocation', '')
            pain_character = survey.get('painCharacter', [])
            pain_duration = survey.get('painDuration', '')
            pain_triggers = survey.get('painTriggers', '')
            pain_relief = survey.get('painRelief', '')
            functional_impact = survey.get('functionalImpact', '')
            
            # 评估结果
            max_pain_score = survey.get('maxPainScore', '')
            pain_level = survey.get('painLevel', '')
            pain_level_range = survey.get('painLevelRange', '')
            recommendations = survey.get('recommendations', [])
            
            # 记录人信息
            recorder_name = survey.get('recorderName', '')
            recorder_position = survey.get('recorderPosition', '')
            recorder_institution = survey.get('recorderInstitution', '')
            recorder_contact = survey.get('recorderContact', '')
            
            # 处理疼痛性质（多选）
            pain_character_text = ''
            if isinstance(pain_character, list) and pain_character:
                character_labels = [character_mapping.get(char, char) for char in pain_character]
                pain_character_text = '; '.join(character_labels)
            
            # 处理疼痛持续时间
            pain_duration_text = duration_mapping.get(pain_duration, pain_duration)
            
            # 处理建议措施
            recommendations_text = ''
            if isinstance(recommendations, list) and recommendations:
                recommendations_text = '; '.join(recommendations)
            
            # 生成NRS评分答案描述
            def get_nrs_answer(score):
                if score == '' or score is None:
                    return ''
                score = int(score)
                if score == 0:
                    return f"{score}分 (无疼痛)"
                elif 1 <= score <= 3:
                    return f"{score}分 (轻度疼痛)"
                elif 4 <= score <= 6:
                    return f"{score}分 (中度疼痛)"
                elif 7 <= score <= 10:
                    return f"{score}分 (重度疼痛)"
                else:
                    return f"{score}分"
            
            row = [
                patient_name, age, gender_text, diagnosis, phone, record_time, remarks,
                current_pain, get_nrs_answer(current_pain),
                worst_pain_24h, get_nrs_answer(worst_pain_24h),
                least_pain_24h, get_nrs_answer(least_pain_24h),
                average_pain_24h, get_nrs_answer(average_pain_24h),
                rest_pain, get_nrs_answer(rest_pain),
                activity_pain, get_nrs_answer(activity_pain),
                pain_location, pain_location,
                pain_character_text, pain_character_text,
                pain_duration_text, pain_duration_text,
                pain_triggers, pain_triggers,
                pain_relief, pain_relief,
                functional_impact, get_nrs_answer(functional_impact),
                max_pain_score, pain_level, pain_level_range, recommendations_text,
                recorder_name, recorder_position, recorder_institution, recorder_contact
            ]
            
            # 转义CSV特殊字符
            escaped_row = []
            for field in row:
                field_str = str(field) if field is not None else ''
                if ',' in field_str or '"' in field_str or '\n' in field_str:
                    field_str = '"' + field_str.replace('"', '""') + '"'
                escaped_row.append(field_str)
            
            csv_content += ",".join(escaped_row) + "\n"
        
        return csv_content
    
    @staticmethod
    def generate_individual_report(survey: dict) -> str:
        """生成个人评估报告"""
        score = FrailtyService.calculate_frailty_score(survey)
        result = FrailtyService.get_frailty_result(score)
        
        # 计算BMI
        bmi = ""
        if survey.get('height') and survey.get('weight'):
            height_m = survey['height'] / 100
            bmi_value = survey['weight'] / (height_m ** 2)
            bmi = f"{bmi_value:.1f}"
        
        report = f"""Fried衰弱评估个人报告

=== 基本信息 ===
问答编号：{survey.get('surveyId', '')}
生成时间：{datetime.now().strftime('%Y/%m/%d %H:%M:%S')}
记录人姓名：{survey.get('recorderName', '')}
记录人职务/身份：{survey.get('recorderPosition', '')}
所属机构：{survey.get('recorderInstitution', '')}
联系方式：{survey.get('recorderContact', '')}
记录时间：{survey.get('recordTime', '')}

=== 被评估人信息 ===
姓名：{survey.get('patientName', '')}
年龄：{survey.get('age', '')}岁
性别：{survey.get('gender', '')}
身高：{survey.get('height', '')}cm
体重：{survey.get('weight', '')}kg
BMI：{bmi}
联系电话：{survey.get('phone', '')}
备注：{survey.get('remarks', '')}

=== 评估结果 ===
总分：{score}/5
诊断结果：{result}

=== 详细评估结果 ===
1. 体重下降：{'是' if survey.get('weightLoss') == 1 else '否'}
2. 行走时间：{survey.get('walkTime', 0)}分 ({'阳性' if survey.get('walkTime') == 1 else '阴性'})
3. 握力：{survey.get('gripStrength', 0)}分 ({'阳性' if survey.get('gripStrength') == 1 else '阴性'})
4. 体力活动：{survey.get('physicalActivity', 0)}分 ({'阳性' if survey.get('physicalActivity') == 1 else '阴性'})
5. 疲乏评估：
   疲乏评分1：{survey.get('fatigue1', 0)}分
   疲乏评分2：{survey.get('fatigue2', 0)}分

=== 评分标准 ===
• 具备5条中3条及以上：衰弱综合征
• 不足3条：衰弱前期
• 0条：无衰弱健康老人
"""
        
        return report